package com.itheima.controller;

import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 显示订单详情
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model) {
        Order order = orderService.findById(id);
        model.addAttribute("order", order);
        return "order/detail";
    }
    
    /**
     * 根据客户ID查询订单
     */
    @GetMapping("/customer/{customerId}")
    public String findByCustomerId(@PathVariable("customerId") Integer customerId, Model model) {
        List<Order> orders = orderService.findByCustomerId(customerId);
        model.addAttribute("orders", orders);
        model.addAttribute("customerId", customerId);
        return "order/list";
    }
    
    /**
     * 根据订单状态查询
     */
    @GetMapping("/status")
    public String findByStatus(@RequestParam("status") String status, Model model) {
        List<Order> orders = orderService.findByStatus(status);
        model.addAttribute("orders", orders);
        model.addAttribute("status", status);
        return "order/list";
    }
    
    /**
     * 根据客户ID和订单状态查询
     */
    @GetMapping("/search")
    public String search(
            @RequestParam(value = "customerId", required = false) Integer customerId,
            @RequestParam(value = "status", required = false) String status,
            Model model) {
        List<Order> orders;
        
        if (customerId != null && status != null && !status.trim().isEmpty()) {
            orders = orderService.findByCustomerIdAndStatus(customerId, status);
        } else if (customerId != null) {
            orders = orderService.findByCustomerId(customerId);
        } else if (status != null && !status.trim().isEmpty()) {
            orders = orderService.findByStatus(status);
        } else {
            // 如果没有提供任何查询条件，返回空列表
            orders = List.of();
        }
        
        model.addAttribute("orders", orders);
        model.addAttribute("customerId", customerId);
        model.addAttribute("status", status);
        
        return "order/list";
    }
}
